from app import app
from flask import render_template, flash, redirect, url_for,request
from app.forms import LoginForm,Registfrom

from flask_login import current_user,login_user,logout_user,login_required
from app.models import User
from app import common
from werkzeug.urls import url_parse
from app import  db


@app.route('/')
@app.route('/index')

def index():
    title="闫利敏的博客"
    user = {'uname':'duke'}
    posts = [
        {
            'author':{'username':'刘'},
            'body':'这是模板模块中的循环例子～1'
        },
        {
            'author': {'username': '忠强'},
            'body': '这是模板模块中的循环例子～2'
        }
    ]
    return render_template('index.html',title=title,users=user,posts=posts)
@app.route('/login',methods=['GET','POST'])
def login():
    common.checkloing()
    form=LoginForm()
    if form.validate_on_submit():
        user=User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash("用户名或密码错误111"+form.username.data)
            return redirect(url_for('login'))
        else:
            flash('zhengque')
            login_user(user,remember=form.remember_me.data)
            next_page=request.args.get('next')
            if not next_page or url_parse(next_page).netloc !='':
                next_page=url_for('index')
            return redirect(next_page)
        #flash('用户名是：{}，密码是：{}，是否记住：{}'.format(form.username.data,form.password.data, form.remember_me.data))

    return render_template('login.html',title='登录',form=form)

@app.route('/register',methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form=Registfrom()
    if form.validate_on_submit():
        user=User(username=form.username.data,email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('成功')
        return redirect(url_for('login'))
    return render_template('register.html',title='注册',form=form)

@app.route('/users/<id>')
@login_required
def users(id):
    user=User.query.filter_by(id=id).first_or_404()
    return render_template('users.html',user=user,posts=user.posts.all())

@app.route('/loginout')
def loginout():
    logout_user()
    return redirect(url_for('index'))